package cn.wenhe9.yygh.hosp.service.impl;

import cn.wenhe9.yygh.cmn.client.DictFeignClient;
import cn.wenhe9.yygh.common.exception.YyghException;
import cn.wenhe9.yygh.common.result.ResultCodeEnum;
import cn.wenhe9.yygh.common.result.ResultResponse;
import cn.wenhe9.yygh.hosp.repository.HospitalRepository;
import cn.wenhe9.yygh.hosp.service.HospitalService;
import cn.wenhe9.yygh.model.hosp.BookingRule;
import cn.wenhe9.yygh.model.hosp.Hospital;
import cn.wenhe9.yygh.model.hosp.HospitalSet;
import cn.wenhe9.yygh.model.vo.hosp.HospitalQueryVo;
import cn.wenhe9.yygh.model.vo.order.SignInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author DuJinliang
 * 2022/2/18
 */
@Service
public class HospitalServiceImpl implements HospitalService {

    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private HospitalRepository hospitalRepository;

    @Resource
    private DictFeignClient dictFeignClient;

    @Override
    public ResultResponse saveHosp(Map<String, Object> parameterMap) throws JsonProcessingException {

        String bookingRuleJson = (String) parameterMap.get("bookingRule");
        BookingRule bookingRule = objectMapper.readValue(bookingRuleJson, BookingRule.class);

        parameterMap.remove("bookingRule");
        String json = objectMapper.writeValueAsString(parameterMap);

        Hospital hospital = objectMapper.readValue(json, Hospital.class);
        hospital.setBookingRule(bookingRule);

        String hoscode = hospital.getHoscode();
        Optional<Hospital> hospitalOptional = hospitalRepository.findHospitalByHoscode(hoscode);
        if (hospitalOptional.isPresent()){
            hospital = hospitalOptional.get();
            hospital.setUpdateTime(new Date());

            hospitalRepository.save(hospital);
        }else {
            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);

            hospitalRepository.save(hospital);
        }
        return ResultResponse.ok();
    }

    @Override
    public Hospital getByHoscode(String hoscode) {
        Optional<Hospital> hospitalOptional = hospitalRepository.findHospitalByHoscode(hoscode);
        if (hospitalOptional.isPresent()){
            return hospitalOptional.get();
        }
        return null;
    }

    @Override
    public ResultResponse findHospitalsByPage(HospitalQueryVo hospitalQueryVo, int page, int limit) {
        Pageable pageable = PageRequest.of(page-1, limit);
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo, hospital);
        Example<Hospital> example = Example.of(hospital, exampleMatcher);

        Page<Hospital> hospitalPage = hospitalRepository.findAll(example, pageable);

        //获取查询list集合，遍历进行医院等级的封装
        hospitalPage.getContent().forEach(item -> {
            this.setHospitalHosType(item);
        });

        return ResultResponse.ok(hospitalPage);
    }

    @Override
    public ResultResponse updateStatus(String id, Integer status) {
        //根据id查询医院信息
        Optional<Hospital> hospitalOptional = hospitalRepository.findById(id);
        if (!hospitalOptional.isPresent()) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        Hospital hospital = hospitalOptional.get();
        //设置修改的值
        hospital.setStatus(status);
        hospital.setUpdateTime(new Date());

        hospitalRepository.save(hospital);

        return ResultResponse.ok();
    }

    @Override
    public ResultResponse findHospDetail(String id) {
//        Optional<Hospital> hospitalOptional = hospitalRepository.findById(id);
        Optional<Hospital> hospitalOptional = hospitalRepository.findHospitalByHoscode(id);
        Map<String, Object> result = new HashMap<>();

        if (!hospitalOptional.isPresent()){
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }

        Hospital hospital = hospitalOptional.get();
        result.put("hospital", hospital);
        result.put("bookingRule", hospital.getBookingRule());
        hospital.setBookingRule(null);

        return ResultResponse.ok(result);
    }

    @Override
    public String getHospname(String hoscode) {

        Optional<Hospital> hospitalOptional = hospitalRepository.findHospitalByHoscode(hoscode);
        if (hospitalOptional.isPresent()){
            Hospital hospital = hospitalOptional.get();
            return hospital.getHosname();
        }

        return "";
    }

    @Override
    public ResultResponse findByHosname(String hosname) {
        List<Hospital> hospitalList = hospitalRepository.findHospitalsByHosnameLike(hosname);
        return ResultResponse.ok(hospitalList);
    }


    private void setHospitalHosType(Hospital hospital){
        String hostypeString = dictFeignClient.getName("Hostype", hospital.getHostype());
        String provinceString = dictFeignClient.getName(hospital.getProvinceCode());
        String cityString = dictFeignClient.getName(hospital.getCityCode());
        String districtString = dictFeignClient.getName(hospital.getDistrictCode());

        hospital.getParam().put("fullAddress", provinceString + cityString + districtString);
        hospital.getParam().put("hostypeString", hostypeString);
    }


}
